package com.hxzy.controller.userinfo;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.common.BaseServlet;
import com.hxzy.common.ResultAjax;
import com.hxzy.util.BeanValidatorUtil;
import com.hxzy.entity.UserInfo;
import com.hxzy.service.UserInfoService;
import com.hxzy.service.impl.UserInfoServiceImpl;
import org.mindrot.jbcrypt.BCrypt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * @Description:
 * @Author: ykj
 * @Date: 2022/3/1 14:40
 */
@WebServlet(urlPatterns = "/userinfoWeb/add")
public class SearchAdd extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        try{
            //搜集数据
            UserInfo userInfo = super.CollectiongParameterVlues(req, UserInfo.class);

            //做数据有效性的验证
            Set<String> validator=BeanValidatorUtil.validator(UserInfo.class, userInfo);

            if (validator.isEmpty()){

            ////修改明文密码为加密的密码(长度验证)
            String hashpw = BCrypt.hashpw(userInfo.getLoginPwd(), BCrypt.gensalt());
            userInfo.setLoginPwd(hashpw);

            //调用和新增操作
            UserInfoService service=new UserInfoServiceImpl();
            int insert = service.insert(userInfo);
            ResultAjax resultAjax=null;

            if (insert>0){
                resultAjax = ResultAjax.success();
            }else {
                resultAjax  = ResultAjax.error("操作失败");
            }
            //向客户端传输json数据
            super.render(resp, JSONObject.toJSONString(resultAjax));
            }else {
                //验证失败
                //迭代错误信息
                String next = validator.iterator().next();
                ResultAjax error = ResultAjax.error(501, next);
                String string = JSONObject.toJSONString(error);
                super.render(resp,string);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}
